<template>
  <el-dialog
  :title="showTitle"
  :visible="showDialog"
  :before-close="btnCancel">
  <!-- 表单 -->
  <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
    <el-form-item label="角色名称" prop="name">
      <el-input v-model="roleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="角色描述">
      <el-input v-model="roleForm.description"></el-input>
    </el-form-item>
  </el-form>

  <!-- 插槽 -->
  <el-row slot="footer" type="flex" justify="center">
    <el-col :span="6">
      <el-button size="small" @click="btnCancel">取消</el-button>
      <el-button size="small" type="primary" @click="btnOK">确定</el-button>
    </el-col>
  </el-row>
</el-dialog>
</template>

<script>
import { updateRole, getRoleDetail, addRole } from '@/api/setting'
export default {
  name: 'addRole',
  data() {
    return {
      // 专门接收新增或者编辑的编辑的表单数据
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
    }
  },
  props: {
    showDialog: {
      type: Boolean,
      required: true
    }
  },
  computed: {
    showTitle() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  methods: {
    btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }

      // 清空校验规则
      this.$refs.roleForm.resetFields()
      // 关闭弹出框
      this.$emit('update:showDialog', false)
    },
    async btnOK() {
      try {
      await this.$refs.roleForm.validate()
        if (this.roleForm.id) {
          // 编辑角色模块
          await updateRole(this.roleForm)
        } else {
          // 新增角色模块
          await addRole(this.roleForm)
        }
        this.$emit('update:showDialog', false) // 关闭弹出框
        this.$emit('getRoleList') // 重新获取数据
        this.$message.success('操作成功') // 提示操作成功
      } catch (error) {
        console.log(error);
      }
    },
    async getRoleDetail(id) {
      this.roleForm = await getRoleDetail(id)
    }
  }
}
</script>

<style scoped>

</style>